<template>
  <div class="system-info-chart">
    <div class="system-info-title">
      <span>{{ title }}</span>
    </div>
    <div class="system-info-echart">
      <div ref="infoRef" style="width: 200px; height: 200px"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import resize from "@/mixins/resize";

export default {
  mixins: [resize],
  props: {
    title: {
      type: String,
      required: true,
    },
    chartTitle: {
      type: String,
      required: true,
    },
    percent: {
      type: [Number, String],
      required: true,
    },
  },
  watch: {
    percent: {
      handler(value) {
        this.$nextTick(() => {
          this.init();
        });
      },
      immediate: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  beforeDestroy() {
    this.destroyChart();
  },
  methods: {
    init() {
      if (!this.chart) {
        this.initChart();
      }

      const options = {
        tooltip: {
          show: false,
        },
        legend: {
          show: false,
        },
        title: {
          text: this.chartTitle,
          bottom: 6,
          left: "center",
          textStyle: {
            fontWeight: "500",
            fontSize: 14,
            color: "#fff",
          },
        },
        series: [
          {
            type: "gauge",
            radius: "80%",
            splitLine: { show: false },
            axisTick: { show: false },
            axisLabel: { show: false },
            pointer: { show: false },
            progress: { show: true, roundCap: true, width: 10 },
            detail: {
              valueAnimation: true,
              formatter: "{value}%",
              fontSize: 20,
              offsetCenter: ["0", "0"],
              color: "#fff",
            },
            axisLine: {
              roundCap: true,
              lineStyle: {
                width: 10,
              },
            },
            data: [
              {
                value: this.percent,
                itemStyle: {
                  color: "#1980ff",
                },
              },
            ],
            label: false,
            startAngle: 225,
            endAngle: -45,
            silent: true,
          },
        ],
      };

      this.chart.showLoading();

      this.chart.setOption(options);

      this.chart.hideLoading();
    },
    initChart() {
      this.chart = echarts.init(this.$refs.infoRef);
    },
    destroyChart() {
      if (!this.chart) {
        return;
      }

      this.chart.dispose();
      this.chart = null;
    },
  },
};
</script>
